package com.lims.action.common;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionContext;
import com.lims.action.base.BaseAction;
import com.lims.po.admin.Admin;
import com.lims.po.common.Department;
import com.lims.po.common.EnParty;
import com.lims.po.common.Project;
import com.lims.po.common.Sample;
import com.lims.po.common.SampleType;
import com.lims.po.common.Task;
import com.lims.po.common.TestItem;
import com.lims.po.common.TestOfProject;
import com.lims.util.DownloadFileAction;
import com.lims.util.MD5;



public class ProjectAction extends DownloadFileAction {
	
	private static final String INIT_SHOW_PROJECT="initShowProject";
	private static final String INIT_ADD_PROJECT="initAddProject";
	private static final String SHOW_TEST_BY_SAMPLE="showTestBySample";
	private static final String DO_DETAIL_PROJECT="doDetailProject";
	private static final String INIT_FOR_TASK="initForTask";
	private static final String DO_DETAIL_TASK="doDetailTask";
	private static final String SHOW_TASK="showTask";
	private static final String DO_ADD_REPORT_FOR_TASK="doAddReportForTask";
	private static final String SHOW_TASK_REPORT="showTaskReport";
	private static final String DO_ADD_REPORT_FOR_PROJECT="doAddReportForProject";
	private Project project;
	private List<SampleType> sampleTypes;
	private List<TestItem> testItems;
	private SampleType sampleType;
	private EnParty enParty;
	private Sample sample;
	private List<Project> projects;
	private List<Department> departments;
	private String check;
	private Task task;
	private List<Task> tasks;
	private Department department;
	private static final Log log = LogFactory.getLog(ProjectAction.class);
	
	private static final String	CLASS_NAME=ProjectAction.CLASS_NAME;
	
	
	// ////////////////////////////////////////////////////////
	// 以下三个成员用于文件上传
	// ////////////////////////////////////////////////////////
	private File doc;
	private String fileName;
	private String contentType;
	
	
	public String initShowProject(){
		projects=projectService.selectAll();
		return INIT_SHOW_PROJECT;
	}
	
	public String initForAddProject(){
		sampleTypes=sampleTypeService.selectAll();
		return INIT_ADD_PROJECT;
	}
	public String doAddProject(){
		String []testItemIds=getParameterValues("testItem");
		Set<TestItem> sets=new HashSet<TestItem>();
		for (String string : testItemIds) {
			sets.add(testItemService.selectTestItemById(Integer.parseInt(string)));
		}
		List<TestOfProject> list = new ArrayList<TestOfProject>();
		if (testItemIds != null) {
			for (int i = 0; i < testItemIds.length; i++) {
				TestOfProject testOfProject = new TestOfProject();
				testOfProject.setTestItem(testItemService.selectTestItemById(Integer.parseInt(testItemIds[i])));
				testOfProject.setProject(project);
				list.add(testOfProject);
			}
		}
		project.setStatusId(1);
		project.setIsCheck("false");
		projectService.saveProject(project,sample,enParty,list);
		return INIT_ADD_PROJECT;
	}
	public String doCheckProject(){
		String isCheck=project.getIsCheck();
		project=projectService.selectProjectById(project.getPid());
		project.setIsCheck(isCheck.trim().toLowerCase());
		projectService.updateProject(project);
		projects=projectService.selectAll();
		return INIT_SHOW_PROJECT;
	}
	public String initForTask(){
		project=projectService.selectProjectById(project.getPid());
		departments=departmentService.selectAllByProjectId(project.getPid());
		if(departments==null||departments.size()==0){
			projects=projectService.selectAll();
			return INIT_SHOW_PROJECT;
		}
		return INIT_FOR_TASK;
	}
	
	public String doAddTask(){
		project=projectService.selectProjectById(project.getPid());
		task.setSampleNo(project.getProno());
		task.setProject(project);
		taskService.saveTask(task);
		departments=departmentService.selectAll();
		return INIT_FOR_TASK;
	}
	public String doDetailTask(){
		task=taskService.selectTaskById(task.getPid());
		project=task.getProject();
		return DO_DETAIL_TASK;
	}
	public String showTaskByDepartment(){
		tasks=taskService.selectAllByDepartmentId(department.getPid());
		return SHOW_TASK;
	}
	public String 	doTaskForProject(){
		project=projectService.selectProjectById(project.getPid());
		project.setStatusId(2);
		projectService.updateProject(project);
		projects=projectService.selectAll();
		return INIT_SHOW_PROJECT;
	}
	
	public String 	checkTaskForProject(){
		project=projectService.selectProjectById(project.getPid());
		project.setStatusId(check.equals("true")?3:1);
		projectService.updateProject(project);
		projects=projectService.selectAll();
		return INIT_SHOW_PROJECT;
	}
	
	public String doAddReportForTask(){
		task=taskService.selectTaskById(task.getPid());
		String targetDirectory = "d:\\file\\";
		String targetFileName = task.getProject().getProno() + "-" + this.generateFileName(fileName);// 命名规则：PaperNo-yyyyMMdd-HHmmss-XXXX
		File target = new File(targetDirectory, targetFileName);

		try {
			FileUtils.copyFile(doc, target);
			task.setReportFileName(targetFileName);
			taskService.updateTask(task);
			tasks=taskService.selectAllByDepartmentId(department.getPid());
		} catch (Exception e) // 如果上传文件出现异常，就发出警告，重新上传
		{
			log.error(CLASS_NAME + "-->doAddReportForTask:" + e.toString());
		}
		
		return SHOW_TASK;
	}
	public String initForAddReportForTask(){
		task=taskService.selectTaskById(task.getPid());
		return DO_ADD_REPORT_FOR_TASK;
	}
	
	public String showTaskReport(){
		project=projectService.selectProjectById(project.getPid());
		return SHOW_TASK_REPORT;
	}
	
	
	
	public String doAddReportForProject(){
		project=projectService.selectProjectById(project.getPid());
		String targetDirectory = "d:\\file\\";
		String targetFileName = project.getProno() + "-" + this.generateFileName(fileName);// 命名规则：PaperNo-yyyyMMdd-HHmmss-XXXX
		File target = new File(targetDirectory, targetFileName);

		try {
			FileUtils.copyFile(doc, target);
			project.setReportFileName(targetFileName);
			project.setReportIsCheck("false");
			projectService.updateProject(project);
			projects=projectService.selectAll();
		} catch (Exception e) // 如果上传文件出现异常，就发出警告，重新上传
		{
			log.error(CLASS_NAME + "-->doAddReportForTask:" + e.toString());
		}
		
		return INIT_SHOW_PROJECT;
	}
	public String initForAddReportForProject(){
		project=projectService.selectProjectById(project.getPid());
		return DO_ADD_REPORT_FOR_PROJECT;
	}
	
	public String doCheckProjectReport(){
		String isCheck=project.getReportIsCheck();
		project=projectService.selectProjectById(project.getPid());
		project.setReportIsCheck(isCheck.trim().toLowerCase());
		projectService.updateProject(project);
		projects=projectService.selectAll();
		return INIT_SHOW_PROJECT;
	}
	
	
	public String downLoadFile(){
		isNeedSave=true;
		return "downLoad";
	}
	
	public String showTestBySample(){
		sampleType=sampleTypeService.selectSampleTypeById(sampleType.getPid());
		testItems=testItemService.selectBySampleType(sampleType.getPid());
		return SHOW_TEST_BY_SAMPLE;
	}
	
	public String doDetailProject(){
		project=projectService.selectProjectById(project.getPid());
		return DO_DETAIL_PROJECT;
	}
	
	private String generateFileName(String fileFileName) {

		DateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss");
		String formatDate = format.format(new Date());

		int random = new Random().nextInt(10000); // 保证4位数
		if (random <= 999) {
			random = random + 1000;
		}

		int position = fileFileName.lastIndexOf(".");

		String extension = fileFileName.substring(position);

		return formatDate + "-" + random + extension;

	}
	public Project getProject() {
		return project;
	}

	public void setProject(Project project) {
		this.project = project;
	}

	public List<SampleType> getSampleTypes() {
		return sampleTypes;
	}

	public void setSampleTypes(List<SampleType> sampleTypes) {
		this.sampleTypes = sampleTypes;
	}

	public List<TestItem> getTestItems() {
		return testItems;
	}

	public void setTestItems(List<TestItem> testItems) {
		this.testItems = testItems;
	}

	public SampleType getSampleType() {
		return sampleType;
	}

	public void setSampleType(SampleType sampleType) {
		this.sampleType = sampleType;
	}

	public EnParty getEnParty() {
		return enParty;
	}

	public void setEnParty(EnParty enParty) {
		this.enParty = enParty;
	}

	public Sample getSample() {
		return sample;
	}

	public void setSample(Sample sample) {
		this.sample = sample;
	}

	public List<Project> getProjects() {
		return projects;
	}

	public void setProjects(List<Project> projects) {
		this.projects = projects;
	}

	public String getCheck() {
		return check;
	}

	public void setCheck(String check) {
		this.check = check;
	}

	public List<Department> getDepartments() {
		return departments;
	}

	public void setDepartments(List<Department> departments) {
		this.departments = departments;
	}

	public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}

	public List<Task> getTasks() {
		return tasks;
	}

	public void setTasks(List<Task> tasks) {
		this.tasks = tasks;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	public void setDoc(File file) {
		this.doc = file;
	}

	public void setDocFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setDocContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public File getDoc() {
		return doc;
	}

}
